var currentStatus:String;
var previewFillingMaskBar;
var cacheFillingMaskBar;
var progressFillingMaskBar;
var previewDuration:Number;
var currentFilteredAudioObj;
var timeDisplay:TextField;
var progressDisplay:TextField;

var playerEngineRunning:Boolean;
var convertorRunning:Boolean;

var onceFlag:Boolean;

// var convertedResource:Boolean;

function init(param, data, slot)
{
	Packages.model.Context.activeContent=this;

	/*// Condition.check
	if (Packages.model.UserProfile.RecordingCollabId==null) 
	{
		Packages.components.SceneAgent.loadScene("content/HomePage", true);
		return;
	}
	// */
	
	// UI.init
	var basic=Packages.system.mlf.GateKeeper.scanElement(this._name, "basic");
	Packages.system.display.JAccordion.initialize(basic);
	
	// Render.init
	Packages.system.render.Filter.titleFilter(Packages.system.mlf.GateKeeper.scanElement(this._name, "PostProductionTitle"));
	Packages.system.render.Filter.titleFilter(Packages.system.mlf.GateKeeper.scanElement(this._name, "myReadjoyTitle"));
	Packages.system.display.SceneTransition.rollOut();

	// Event.init
	var evtTargetArr:Array=new Array();
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "Prepairation_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "OnAir_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "PostProduction_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "Publish_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "back_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "sendMsgSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "quickConvertSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "fullConvertSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "previewSpot"));
	Packages.system.events.StateFulButtonEvent.initialize(evtTargetArr);

	invokeInitComplete();
}

function dispose()
{
	Packages.system.mlf.GateKeeper.removeListener("onReleaseButtonEvent", this);

	// Packages.modula.task.Common.stopCollabEnvironment();
	// player.stop
	Packages.system.mlf.GateKeeper.playerController("Stop");
}

function invokeInitComplete()
{
	Packages.system.mlf.GateKeeper.addListener("onReleaseButtonEvent", this);

	// check the collab env and initialize the env
	Packages.modula.task.Common.checkCollabEnvironment(this._name);

	// init the timedisplay of preview audio
	previewDuration=Packages.modula.task.Composition.processData.duration;
	timeDisplay=mlf.gatekeeper.native.Caller.scanElement(this._name, "timedisplay");
	displayTimePeriod(timeDisplay, 0, previewDuration);
	progressDisplay=mlf.gatekeeper.native.Caller.scanElement(this._name, "ptimedisplay");
	displayTimePeriod(progressDisplay, 0, previewDuration);
	
	var previewFillingBar=mlf.gatekeeper.native.Caller.scanElement(this._name, "fillbar");
	previewFillingMaskBar=previewFillingBar.duplicateMovieClip("masker", previewFillingBar._parent.getNextHighestDepth());
	previewFillingBar.setMask(previewFillingMaskBar);

	var cacheFillingBar=mlf.gatekeeper.native.Caller.scanElement(this._name, "cachebar");
	cacheFillingMaskBar=cacheFillingBar.duplicateMovieClip("cachemasker", cacheFillingBar._parent.getNextHighestDepth());
	cacheFillingBar.setMask(cacheFillingMaskBar);

	var progressFillingBar=mlf.gatekeeper.native.Caller.scanElement(this._name, "pfillbar");
	progressFillingMaskBar=progressFillingBar.duplicateMovieClip("masker", progressFillingBar._parent.getNextHighestDepth());
	progressFillingBar.setMask(progressFillingMaskBar);

	//
	currentStatus="idle";		//
	currentFilteredAudioObj=new Object();		//
}

function displayTimePeriod(display_tf:TextField, progress:Number, duration:Number)
{
	display_tf.text="[ "+calculateTimeFormat(progress)+" / "+calculateTimeFormat(duration)+" ]";
}

function calculateTimeSecond(tformat:String):Number
{
	var tEleArr=tformat.split(":");
	var totalSeconds=Number(tEleArr[2])+Number(tEleArr[1])*60+Number(tEleArr[0])*3600;
	// trace("totalSeconds: "+totalSeconds);
	return totalSeconds;
}

function calculateTimeFormat(seconds:Number):String
{
	var result:String="";

	var hour=Math.floor(seconds/3600);
	if (hour.toString().length==1)
	{
		result="0"+hour;
	}
	else result=hour;
	var minute=Math.floor((seconds-hour*3600)/60);
	if (minute.toString().length==1)
	{
		result+=":0"+minute;
	}
	else result+=":"+minute;
	var second=Math.floor(seconds-hour*3600-minute*60);
	if (second.toString().length==1)
	{
		result+=":0"+second;
	}
	else result+=":"+second;

	return result;
}

function previewAudio()
{
	if (currentStatus=="idle" && !playerEngineRunning)
	{
		var audioContent;
		if (currentFilteredAudioObj.filteredAudioId==null)
		{
			audioContent=generateMLVbyAudioId(Packages.modula.task.Composition.audioId, "flv");
		}
		else 
		{
			audioContent=generateMLVbyAudioId(currentFilteredAudioObj.filteredAudioId, "mp3");
		}
		var playArea=mlf.gatekeeper.native.Caller.scanElement(this._name, "previewAudio");
		// trace("playArea: "+playArea);
		var param=new Object();
		param.target=playArea;
			
		param.type="file";
		param.source=new XML(audioContent);

		Packages.log(Packages.system.mlf.GateKeeper.playerController("Version"), "info");
		Packages.system.mlf.GateKeeper.addListener("onPlayback", this);
		 Packages.system.mlf.GateKeeper.playerController("Open", param);

		currentStatus="play";
		var previewHint=mlf.gatekeeper.native.Caller.scanElement(this._name, "previewHint");
		previewHint.htmlText=Packages.system.mlf.GateKeeper.scanDictionary(previewFillingMaskBar, "Stop");
	}
	else if (currentStatus=="play")
	{
		Packages.system.mlf.GateKeeper.playerController("Stop");
		currentStatus="idle";
		var previewHint=mlf.gatekeeper.native.Caller.scanElement(this._name, "previewHint");
		previewHint.htmlText=Packages.system.mlf.GateKeeper.scanDictionary(previewFillingMaskBar, "Preview");
	}
}

function invokeRollOver(param, data, slot)
{
	Mouse.show();
}

function invokeRollOut(param, data, slot)
{
	Mouse.hide();
}

function mSeek(param, data, slot)
{
	var num=Math.floor(data.pos/previewFillingMaskBar._width*previewDuration);
	 Packages.system.mlf.GateKeeper.playerController("Seek", num);
}

function onPlayback(obj)
{
	// trace("onPlayback: "+obj.param.type);
	if (obj.param.type=="playback")
	{
		
		/*if (previewDuration==0) previewDuration=applications.prototype.Logic.run("Duration");*/
		previewFillingMaskBar._x=obj.param.param/previewDuration*previewFillingMaskBar._width-previewFillingMaskBar._width+125;
		displayTimePeriod(timeDisplay, Number(obj.param.param), Number(previewDuration));

	}
	else if (obj.param.type=="progress")
	{
		var totalBytes=obj.param.param.bytesLoaded;
		var todoBytes=0;
		var progressStatus=obj.param.param.progress;
		for (var b in progressStatus)
		{
			if (progressStatus[b].bytesTotal!=null)
			{
				todoBytes+=(progressStatus[b].bytesTotal-progressStatus[b].bytesLoaded);
			}
		}
		var cprogress=1-todoBytes/(todoBytes+totalBytes);
		// trace("cprogress: "+cprogress);
		cacheFillingMaskBar._x=cprogress*cacheFillingMaskBar._width-cacheFillingMaskBar._width+125;

		if (!onceFlag && cprogress>0.1 && cprogress<1)
		{
			var mode:Object=new Object();
			mode.processKeeper=Packages.system.mlf.GateKeeper.playerController("Count");
			Packages.system.mlf.GateKeeper.playerController("Mode", mode);
			onceFlag=true;
		}

		if (obj.param.param.unloaded==0)
		{
			var mode:Object=new Object();
			mode.syncRef="audio0";
			Packages.system.mlf.GateKeeper.playerController("Mode", mode);
		}
	}
	else if (obj.param.type=="overPlay")
	{
		// previewDuration=0;
		Packages.system.mlf.GateKeeper.removeListener("onPlayback", this);
		playerEngineRunning=false;
		currentStatus="idle";
		var previewHint=mlf.gatekeeper.native.Caller.scanElement(this._name, "previewHint");
		previewHint.htmlText=Packages.system.mlf.GateKeeper.scanDictionary(previewFillingMaskBar, "Preview");
	}
	else if (obj.param.type=="readyPlay")
	{
		onceFlag=false;
		playerEngineRunning=true;
	}
}

function generateMLVbyAudioId(audioId:String, type:String):String
{
	var duration:Number;
	var tagType:String;
	if (type=="mp3")
	{
		tagType="audio";
		duration=currentFilteredAudioObj.filteredDuration;
		previewDuration=duration;
		// trace("duration: "+duration);
	}
	else // flv type
	{
		tagType=type;
		duration=Packages.modula.task.Composition.processData.duration;
	}
	var mlvString:String="";
	var audioURI:String=Packages.system.mlf.GateKeeper.accessSystemConfig("httpRequest")+"/tmp/audio/"+audioId+"."+type;
	mlvString+="<mlv duration='"+duration+"' name='MLV' info='designed by blue night'>";
	mlvString+="<resource>";
	mlvString+="<"+tagType+" name='audio0' uri='"+audioURI+"'/>";
	mlvString+="</resource>";
	mlvString+="<playback>";
	mlvString+="<clip name='audio0_c1' signpost='0' length='"+duration+"' layer='10' ref='audio0'/>";
	mlvString+="</playback>";
	mlvString+="</mlv>";

	return mlvString;
}

function convertAudio(quickFlag:Boolean)
{
	if (convertorRunning) 
	{
		Packages.modula.MessageCenter.send("UNDER_CONVERTING", 1, 0);
		return;
	}
	// convertFlv2Mp3(data);
	convertorRunning=true;	
	// Packages.system.Platform.messageHint("ReadingRecorder", Packages.system.MLF.scanDictionary(previewFillingMaskBar, "converting"), "warning");	//
	// data generator: sampleRate, bitRate, volume, startTime, endTime
	var data:Object=new Object();
	var sampleRate_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "sampleratev");
	data.sampleRate=sampleRate_tf.text;
	var bitRate_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "bitratev");
	data.bitRate=bitRate_tf.text;
	var volume_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "volv");
	data.volume=volume_tf.text;
	if (quickFlag)
	{
		var qcfromHint_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "qcfromHint");
		data.startTime=qcfromHint_tf.text;
		var qctoHint_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "qctoHint");
		data.endTime=qctoHint_tf.text;
	}
	//
	generateCurrentAudioId(data);
}

function generateCurrentAudioId(data)
{
	var refData=data;
	var item=new Object();
	item.type="generateUuid";
	item.param=new Object();
	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		Packages.log("generateAudioId.onResult: "+res.returnObj, "debug");
		if (res.returnObj!=null)
		{
			this.owner.currentFilteredAudioObj.preAssignedAudioId=res.returnObj;
			this.owner.convertFlv2Mp3(refData);
		}
		else 
		{
			this.owner.convertorRunning=false;
			Packages.modula.MessageCenter.send("MP3ID_GENERATION_FAIL", 1, 0);
			Packages.modula.task.Common.sendMsg("MP3ID_GENERATION_FAIL");
		}
	}	
	Packages.system.mlf.GateKeeper.rtmpCaller(item);
}

function convertFlv2Mp3(data)
{
	Packages.modula.MessageCenter.send("CONVERTING_WITH_MP3ID", 1, 0);
	
	var sampleRate=0;
	if (data.sampleRate=="11") sampleRate=11025;
	else if (data.sampleRate=="22") sampleRate=22050;
	else if (data.sampleRate=="44") sampleRate=44100;
	var item=new Object();
	item.type="audioFilter";
	item.param=new Object();
	item.param.input=Packages.modula.task.Composition.audioId+".flv";
	item.param.output=currentFilteredAudioObj.preAssignedAudioId+".mp3";
	item.param.bitRate=data.bitRate.toString();
	item.param.sampleRate=sampleRate.toString();
	item.param.volume=data.volume.toString();
	item.param.startTime=0;
	if (data.startTime!=null)
	{
		item.param.startTime=calculateTimeSecond(data.startTime).toString();
	}
	item.param.startTime=item.param.startTime.toString();
	item.param.duration=-1;
	currentFilteredAudioObj.preAssignedDuration=Packages.modula.task.Composition.processData.duration;
	if (data.endTime!=null)
	{
		item.param.duration=calculateTimeSecond(data.endTime)-calculateTimeSecond(data.startTime);

		currentFilteredAudioObj.preAssignedDuration=item.param.duration;
	}
	item.param.duration=item.param.duration.toString();
	// trace("preAssignedDuration: "+currentFilteredAudioObj.preAssignedDuration);
	//item.param.numChannels=0;
	//item.param.sizeLimit=-1;
	for (var a in item.param)
	{
		Packages.log(a+": "+item.param[a], "debug");
	}

	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		Packages.log("filterAudio.obj.returnCode: "+res.returnCode, "debug");
		if (res.returnCode!=0)
		{
			this.owner.convertorRunning=false;
			Packages.modula.MessageCenter.send("CONVERTING_FAILED", 1, 0);
			Packages.modula.task.Common.sendMsg("CONVERTING_FAILED");
		}
		else 
		{
			Packages.modula.MessageCenter.send("UNDER_CONVERTING", 1, 0);
			Packages.modula.task.Common.sendMsg("UNDER_CONVERTING");
		}
	}   
	// Packages.system.mlf.GateKeeper.rtmpCaller(item);
	Packages.services.RemotingCall.rtmpCaller(item);
	//
	addConvertProgressManualListener();
}

function addConvertProgressManualListener()
{
	startInterval();
}

function startInterval()
{
	Packages.system.mlf.GateKeeper.addListener("onFilterProgressEvent", this);
	
	var noticeEvent:Object=new Object();
	noticeEvent.type="onFilterProgressEvent";
	noticeEvent.gap=1;
	noticeEvent.count=0;
	Packages.system.display.Timer.regNoticeEvent(noticeEvent);
}

function closeInterval()
{
	Packages.system.mlf.GateKeeper.removeListener("onFilterProgressEvent", this);
	Packages.system.display.Timer.removeNoticeEvent("onFilterProgressEvent");
}

function onFilterProgressEvent()
{
	var item=new Object();
	item.type="audioFilterProgress";
	item.param=new Object();
	item.param.input=Packages.modula.task.Composition.audioId+".flv";
	item.param.output=currentFilteredAudioObj.preAssignedAudioId+".mp3";
	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		Packages.log("audioFilterProgress.onResult: "+res.returnObj, "debug");
		if (res.returnObj!=null)
		{
			this.owner.refreshConvertProgress(res.returnObj);
		}
	}	
	Packages.system.mlf.GateKeeper.rtmpCaller(item);
}

function refreshConvertProgress(value)
{
	var percentage:Number=Number(value);
	Packages.log("percentage: "+percentage, "debug");
	Packages.log("preAssignedDuration: "+currentFilteredAudioObj.preAssignedDuration, "debug");
	progressFillingMaskBar._x=percentage/100*progressFillingMaskBar._width-progressFillingMaskBar._width+125;
	displayTimePeriod(progressDisplay, Math.floor(Number(currentFilteredAudioObj.preAssignedDuration)*percentage/100), Number(currentFilteredAudioObj.preAssignedDuration));

	if (percentage==100)
	{
		closeInterval();
		convertorRunning=false;
		if (Packages.model.UserProfile.recordingCollabFlag)
		{
			var args=new Array();
			args.push(currentFilteredAudioObj.preAssignedAudioId);
			args.push(currentFilteredAudioObj.preAssignedDuration);
			Packages.modula.task.Common.updateCollab(this, "invokeConvertComplete", args);
		}
		else invokeConvertComplete(currentFilteredAudioObj.preAssignedAudioId, currentFilteredAudioObj.preAssignedDuration);
		Packages.modula.task.Common.sendMsg("CONVERTING_SUCCESS");
		Packages.modula.MessageCenter.send("CONVERTING_SUCCESS", 1, 0);
	}
}

function invokeConvertComplete(id, duration)
{
	currentFilteredAudioObj.filteredAudioId=id;
	Packages.modula.task.Composition.filteredAudioId=currentFilteredAudioObj.filteredAudioId;
	currentFilteredAudioObj.filteredDuration=duration;
}

function onReleaseButtonEvent(evt:Object, execFlag:Boolean)
{
	// Three types operation for collab env
	// private operation: previewSpot, sendMsgSpot(public), quickConvertSpot(host), fullConvertSpot(host), print(host)
	// public operation: none
	// host operation: none
	
	if (evt.param=="previewSpot")
	{
		previewAudio();
	}
	else if (evt.param=="sendMsgSpot")
	{
		Packages.modula.task.Common.sendMsg();
	}
	else if (evt.param=="quickConvertSpot")
	{
		if (Packages.model.UserProfile.recordingCollabFlag && !Packages.modula.task.Composition.host)
		{
			Packages.modula.MessageCenter.send("YOU_HAVE_NO_RIGHTS_TO_DO_HOST_OPERATION", 1, 0);
			return;
		}

		Packages.modula.task.Common.sendMsg(evt.param.toUpperCase());
		
		convertAudio(true);
	}
	else if (evt.param=="fullConvertSpot")
	{
		if (Packages.model.UserProfile.recordingCollabFlag && !Packages.modula.task.Composition.host)
		{
			Packages.modula.MessageCenter.send("YOU_HAVE_NO_RIGHTS_TO_DO_HOST_OPERATION", 1, 0);
			return;
		}

		Packages.log(Packages.model.UserProfile.data.nickName+".fullConvertSpot... ", "debug");

		Packages.modula.task.Common.sendMsg(evt.param.toUpperCase());

		convertAudio();
	}
	else if (evt.param.indexOf("print")>-1)
	{
		if (Packages.model.UserProfile.recordingCollabFlag && !Packages.modula.task.Composition.host)
		{
			Packages.modula.MessageCenter.send("YOU_HAVE_NO_RIGHTS_TO_DO_HOST_OPERATION", 1, 0);
			return;
		}
		
		var printName=evt.param.substr(0, evt.param.length-6);
		Packages.modula.task.Common.switchRoom(printName, this._name);
	}
}